/**
 * 
 */
package com.xbjtech.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.User;
import com.xbjtech.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;
	
	/**
	 * 获取授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
//		Account account = (Account) principals.getPrimaryPrincipal();
//		// 授权
//		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//		// 从数据库里查询当前登陆的人到底是什么角色，有什么权限
//		if (account.getUsername().equals("mayun")) {
//			info.addRole("taobaorole"); // 这里应该从数据库里面查出来
//		} else if (account.getUsername().equals("suning")) {
//			info.addRole("business"); // 这里应该从数据库里面查出来
//		}
//		return info;
		return null;
	}

	/**
	 * 获取认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		log.info("hashcode:{}", token.hashCode());
		UsernamePasswordToken t = (UsernamePasswordToken) token;
		String username = t.getUsername();
		User user = userService.selectUserByUsername(username);
		if (null == user) {
			throw new UnknownAccountException("用户名不存在");
		}
		if (user.getLocked().compareTo(new Integer(1)) == 0) {
			throw new LockedAccountException("用户已锁定");
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getId() + ""), getName());
	}

}
